package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLoack;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static   {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private  IVoucherOrderService proxy;
//    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);

    private static final ExecutorService SECKILL_ORDER_EXEXUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXEXUTOR.submit(new VoucherOrderHandler());
    }
    private String queuename="stream.orders";
    private  class  VoucherOrderHandler implements Runnable{
         @Override
        public void run() {
            while (true){
                try{
//                    1、获取消息队列得中的订单信息
//                    XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> readList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queuename, ReadOffset.lastConsumed())
                    );
//                    2、判断消息是否获取成功
                    if (readList == null || readList.isEmpty()){
                        continue;
                    }
//                     3、解析订单信息
                    MapRecord<String, Object, Object> record = readList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(),true);
//                    VoucherOrder order = orderTasks.take();
                    handleVoucherOrder(voucherOrder);
                    Long acknowledge = stringRedisTemplate.opsForStream().acknowledge(queuename, "g1", record.getId());
                } catch (Exception e) {
                    log.info("处理订单error");
                    handlePendingList();
                    throw new RuntimeException(e);
                }
            }
        }
    }
    private  void handlePendingList(){
        while (true){
            try{
//                    1、获取pendinglist队列得中的订单信息
//                    XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                List<MapRecord<String, Object, Object>> readList = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queuename, ReadOffset.from("0"))
                );
//                    2、判断消息是否获取成功
                if (readList == null || readList.isEmpty()){
                    break;
                }
//                     3、解析订单信息
                MapRecord<String, Object, Object> record = readList.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(),true);
                handleVoucherOrder(voucherOrder);
                stringRedisTemplate.opsForStream().acknowledge(queuename, "g1", record.getId());
            } catch (Exception e) {
                log.info("处理pending-list error",e);
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder order) {
//        SimpleRedisLoack simpleRedisLoack = new SimpleRedisLoack(stringRedisTemplate,"Order" + userId);
        RLock simpleRedisLoack = redissonClient.getLock("Order" + order.getUserId());
        boolean isLock = simpleRedisLoack.tryLock();
        if (!isLock){
            //获取锁失败，返回错误或重试
            log.error("不允许重复下单");
        }
        try{
            log.info("获取锁成功");
            proxy.createVoucherOrder(order);
        }finally {
            simpleRedisLoack.unlock();
        }

    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        Long res = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        int r = res.intValue();
//        VoucherOrder voucherOrder=new VoucherOrder();
        if (r!=0){
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }
//        long orderId = redisIdWorker.nextId("order");
//        TODO:保存到阻塞队列
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        orderTasks.add(voucherOrder);
        proxy =(IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(orderId);

    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1、查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
//        //2、查询是否开始和结束
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now()))
//        {
//            return Result.fail("优惠券尚未开始");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束");
//        }
//        //3、判断库存是否充足
//        if (voucher.getStock()<1){
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
////        SimpleRedisLoack simpleRedisLoack = new SimpleRedisLoack(stringRedisTemplate,"Order" + userId);
//        RLock simpleRedisLoack = redissonClient.getLock("Order" + userId);
//        boolean isLock = simpleRedisLoack.tryLock();
//        if (!isLock){
//            //获取锁失败，返回错误或重试
//            return Result.fail("请勿重复下单");
//        }
//        try{
//            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }finally {
//            simpleRedisLoack.unlock();
//        }

//    }

    @Override
    @Transactional
    public  void createVoucherOrder(VoucherOrder voucherOrder) {
        //4、一人一单
//        Long userId = UserHolder.getUser().getId();
            Integer count = query().eq("user_id", voucherOrder.getUserId()).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count>0){
                log.info("该用户已经购买过了");
            }
            //扣减库存
            boolean success = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0)
                .update();
            if (!success){
                log.info("活动太火爆了，请稍后再试");
            }
            //5、创建订单
            save(voucherOrder);
    }
}
